package fr.miage.resources;

import java.io.IOException;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import fr.miage.dao.AdressDAO;
import fr.miage.model.Adress;

@Path("/adress")
public class AdressResource {
	
	private AdressDAO adressDAO = new AdressDAO();
	private Logger logger = Logger.getRootLogger();
	
	@GET
	@Path("/{id:[0-9]+}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getAdress(@PathParam(value="id")String idAdress){
		Adress adress = adressDAO.getById(idAdress);
		ObjectMapper mapper = new ObjectMapper();
		if(adress == null){
			return Response.status(404).build();
		}else{
			String fluxJson;
			try {
				fluxJson = mapper.writeValueAsString(adress);
				return Response.ok(fluxJson).build();
			} catch (JsonGenerationException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (JsonMappingException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (IOException e) {
				logger.error(e);
				return Response.status(500).build();
			}
		}
	}
	
	@GET
	@Path("/user/{id:[0-9]+}")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getAdressByUser(@PathParam(value="id")String idUser){
		Adress adress = adressDAO.getAdressByUser(idUser);
		ObjectMapper mapper = new ObjectMapper();
		if(adress == null){
			return Response.status(404).build();
		}else{
			String fluxJson;
			try {
				fluxJson = mapper.writeValueAsString(adress);
				return Response.ok(fluxJson).build();
			} catch (JsonGenerationException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (JsonMappingException e) {
				logger.error(e);
				return Response.status(500).build();
			} catch (IOException e) {
				logger.error(e);
				return Response.status(500).build();
			}
		}
	}
}
